package com.example.javaEE.controller;

import com.example.javaEE.model.Book;
import com.example.javaEE.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/books")
public class BookController {
    @Autowired
    private BookService bookService;

    @GetMapping("/search")
    public List<Book> searchBooks(
            @RequestParam(value = "name", required = false) String name,
            @RequestParam(value = "author", required = false) String author,
            @RequestParam(value = "publisher", required = false) String publisher
    ) {
        if (name != null && !name.isEmpty()) {
            if (author != null && !author.isEmpty()) {
                if (publisher != null && !publisher.isEmpty()) {
                    // 通过书名、作者和出版商搜索
                    return bookService.searchBooksByNameAuthorPublisher(name, author, publisher);
                } else {
                    // 通过书名和作者搜索
                    return bookService.searchBooksByNameAndAuthor(name, author);
                }
            } else if (publisher != null && !publisher.isEmpty()) {
                // 通过书名和出版商搜索
                return bookService.searchBooksByNameAndPublisher(name, publisher);
            } else {
                // 仅通过书名搜索
                return bookService.searchBooksByName(name);
            }
        } else if (author != null && !author.isEmpty()) {
            if (publisher != null && !publisher.isEmpty()) {
                // 通过作者和出版商搜索
                return bookService.searchBooksByAuthorAndPublisher(author, publisher);
            } else {
                // 仅通过作者搜索
                return bookService.searchBooksByAuthor(author);
            }
        } else if (publisher != null && !publisher.isEmpty()) {
            // 仅通过出版商搜索
            return bookService.searchBooksByPublisher(publisher);
        } else {
            // 如果没有提供任何查询条件，则返回空列表或全部书籍列表，视情况而定
            return bookService.getAllBooks();
        }
    }

    @PostMapping
    public Book addBook(@RequestBody Book book) {
        return bookService.addBook(book);
    }

    @PutMapping("/{id}")
    public Book updateBook(@PathVariable Long id, @RequestBody Book book) {
        return bookService.updateBook(id, book);
    }

    @DeleteMapping("/{id}")
    public void deleteBook(@PathVariable Long id) {
        bookService.deleteBook(id);
    }

}